from vec2d import Vec2d
import pygame
from pygame.surface import Surface
import equipment
from pygame.locals import *
from ships.equipment import Generator, BasicGenerator, Thruster
import types
from constants import SCREEN_SIZE

SHIP_IMAGE = "resources/Ivar_cruiser_dark.png"


class Ship():
    
    def __init__(self, *args, **kwargs):
        #Sprite.__init__(self, *args, **kwargs)
        
        # Basic properties
        self.mass = 45000
        
        # Set-up movement vectors
        self.pos = Vec2d(320,320)   # Position of center of ship
        self.velocity = Vec2d(0,0)  # Initial velocity of ship (probably zero)
        self.accel = Vec2d(0,0)     # Initial acceleration of ship (probably zero)
        self.direction = Vec2d(0,1) # Initial direction of ship (as normal vector)
        self.direction = self.direction.normalized() # Normalize just to be sure
        
        self.generator = BasicGenerator()
        self.engine = Thruster(1000, 100000)
        self.targeting = None
        
        # Mounting points (for sprites)
        self.mounts = {'engine': 
                            [(8,37),(28,37)]}
        
        # Set-up the image
        self.image_mstr = pygame.image.load(SHIP_IMAGE)     # Load the image
        #self.image_mstr = self.image_mstr.convert_alpha()   # Convert the bit-scheme or whatevs
        self.image_mstr = self.image_mstr.convert_alpha()         # Convert the bit-scheme or whatevs
        #self.image_mstr.set_colorkey(pygame.Color("white"))
        self.image = self.image_mstr.copy()                 # Store a copy
        self.rect = pygame.Rect((self.pos.x, self.pos.y), self.image_mstr.get_rect().size)
        
        # Set up view vect to follow the player
        self.view_rect = pygame.Rect((0,0), SCREEN_SIZE)
        self.view_rect.center = self.pos.get_coords_tuple()
        
        """ These aren't used in a basic ship, but are here for use as a template
            for consistency --->"""
        self.rear_guns = []
        self.forward_guns = []
        self.side_guns = []
        self.shield = None
        """ <--- """
        
        self.equipment = {"rear_guns": self.rear_guns,
                          "forward_guns":self.forward_guns,
                          "side_guns": self.side_guns,
                          "shield": self.shield,
                          "generator": self.generator,
                          "engine": self.engine,
                          "targeting": self.targeting}
        
        # Ship states
        # The stabalizer automatically applies brakes and corrects trajectories
        self.stabilizer_active = False
        
        # Basic properties
        self.mass = 15000
        
    def update(self, game):
        
        # TODO: This is probably hell on the garbage collector
        image = self.image_mstr.copy()
        
        if game.keys[K_s]:
            self.engine.set_main_level(diff = -0.01)
        elif game.keys[K_w]:
            self.engine.set_main_level(diff = 0.01)      
                         
        if game.keys[K_e]:
            self.engine.set_side_level(diff = 0.01)
        elif game.keys[K_q]:
            self.engine.set_side_level(diff = -0.01)
        else:
            self.engine.set_side_level(level = 0.0)
        
        if game.keys[K_b]:
            self.kill_engines()        
        
        if game.keys[K_a]:
            self.direction.rotate(1)
            self.direction = self.direction.normalized()
            #print "Direction: ",self.direction,"; Angle: ", self.direction.get_angle()
        elif game.keys[K_d]:
            self.direction.rotate(-1)
            self.direction = self.direction.normalized()
            #print "Direction: ",self.direction,"; Angle: ", self.direction.get_angle()

        if game.keys[K_SPACE]:
            # Brakes
            self.stabilizer_active = True
        else:
            self.stabilizer_active = False
            
        #print "direction: ",self.direction," angle: ",self.direction.angle
        thrust = self.engine.get_force(self)
        thrust.rotate(self.direction.angle - 90)
        self.thrust = thrust
        
        #print "force: ", self.thrust
        self.accel = self.thrust
        #print "firing thrusters with accel: ", self.accel
        self.velocity += (self.accel * game.dt)
        self.pos += (self.velocity * game.dt)
        self.rect.center = self.pos.get_screen_coords()
        self.rect.size = self.image.get_size()
        
        if self.engine.image is not None:
            for mount in self.mounts['engine']:
                image.blit(self.engine.image,mount)
        
        del self.image
        self.image = image
        self.rotate()
        
    def draw(self, surface):
        surface.blit(self.image, self.rect)
        
    def rotate(self):
        self.image = pygame.transform.rotate(self.image,int(self.direction.angle - 90))
        
    @property
    def x(self):
        return self.pos.get_screen_coords()[0]
    
    @property
    def y(self):
        return self.pos.get_screen_coords()[1]
    
    def total_mass(self):
        mass = self.mass
        for equip in self.equipment.itervalues():
            if equip is not None and not isinstance(equip, types.ListType):
                mass += equip.mass
        return mass
    
    def total_power_required(self):
        power = 0
        for equip in self.equipment.itervalues():
            power += equip.power_required
        return power
        
    
    def fire(self):
        print "Pew"
        
    def target(self):
        if not self.targeting is None:
            self.targeting.target()
        else:
            print "WITH WHAT!?!?!"
    
    def kill_engines(self):
        self.engine.main_level = 0
        self.engine.side_level = 0        
    
    def stabilize(self):
        force = -(self.accel * self.total_mass())
        